import { useCallback, useEffect, useMemo, useState } from 'react'
import { produce } from 'immer'
import { useBoolean } from 'ahooks'
import useVarList from '../_base/hooks/use-var-list'
import useOutputVarList from '../_base/hooks/use-output-var-list'
import { VarType } from '../../types'
import type { Var } from '../../types'
import { useStore } from '../../store'
import { type Authorization, type Body, BodyType, type MetaOperatorNodeType, MetaClassType, type Method, OutputVar, type Timeout } from './types'
import useKeyValueList from './hooks/use-key-value-list'
import { transformToBodyPayload } from './utils'
import useNodeCrud from '@/components/workflow/nodes/_base/hooks/use-node-crud'
import useOneStepRun from '@/components/workflow/nodes/_base/hooks/use-one-step-run'
import {
  useNodesReadOnly,
} from '@/components/workflow/hooks'

const useConfig = (id: string, payload: MetaOperatorNodeType) => {
  const { nodesReadOnly: readOnly } = useNodesReadOnly()

  const defaultConfig = useStore(s => s.nodesDefaultConfigs)[payload.type]

  const { inputs, setInputs } = useNodeCrud<MetaOperatorNodeType>(id, payload)

  const { handleVarListChange, handleAddVariable } = useVarList<MetaOperatorNodeType>({
    inputs,
    setInputs,
  })

  const [isDataReady, setIsDataReady] = useState(false)

  useEffect(() => {
    console.log('defaultConfig:', defaultConfig);
    const isReady = defaultConfig && Object.keys(defaultConfig).length > 0
    if (isReady) {
      const newInputs = {
        ...defaultConfig,
        ...inputs,
      }
      const bodyData = newInputs.body.data
      if (typeof bodyData === 'string')
        newInputs.body.data = transformToBodyPayload(bodyData, [BodyType.formData, BodyType.xWwwFormUrlencoded].includes(newInputs.body.type))

      setInputs(newInputs)
      setIsDataReady(true)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [defaultConfig])

  const handleMethodChange = useCallback((method: Method) => {
    const newInputs = produce(inputs, (draft: MetaOperatorNodeType) => {
      draft.method = method
    })
    setInputs(newInputs)
  }, [inputs, setInputs])

  const handleMetaClassTypeChange = useCallback((classType: MetaClassType) => {
    const newInputs = produce(inputs, (draft: MetaOperatorNodeType) => {
      draft.class_type = classType
    })
    setInputs(newInputs)
  }, [inputs, setInputs])

  const handleIdentifierChange = useCallback((identifier: string) => {
    const newInputs = produce(inputs, (draft: MetaOperatorNodeType) => {
      draft.identifier = identifier
    })
    setInputs(newInputs)
  }, [inputs, setInputs])

  const handleFieldChange = useCallback((field: string) => {
    return (value: string) => {
      const newInputs = produce(inputs, (draft: MetaOperatorNodeType) => {
        (draft as any)[field] = value
      })
      setInputs(newInputs)
    }
  }, [inputs, setInputs])

  const setTimeout = useCallback((timeout: Timeout) => {
    const newInputs = produce(inputs, (draft: MetaOperatorNodeType) => {
      draft.timeout = timeout
    })
    setInputs(newInputs)
  }, [inputs, setInputs])


  const filterVar = useCallback((varPayload: Var) => {
    return [VarType.string, VarType.number, VarType.secret].includes(varPayload.type)
  }, [])

  const [outputKeyOrders, setOutputKeyOrders] = useState<string[]>([])
  const syncOutputKeyOrders = useCallback((outputs: OutputVar) => {
    setOutputKeyOrders(Object.keys(outputs))
  }, [])
  useEffect(() => {
    if (inputs.identifier) {
      if (inputs.outputs && Object.keys(inputs.outputs).length > 0)
        syncOutputKeyOrders(inputs.outputs)

      return
    }

    const isReady = defaultConfig && Object.keys(defaultConfig).length > 0
    if (isReady) {
      setInputs({
        ...inputs,
        ...defaultConfig,
      })
      syncOutputKeyOrders(defaultConfig.outputs)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [defaultConfig])


  const {
    handleVarsChange,
    handleAddVariable: handleAddOutputVariable,
    handleRemoveVariable,
    isShowRemoveVarConfirm,
    hideRemoveVarConfirm,
    onRemoveVarConfirm,
  } = useOutputVarList<MetaOperatorNodeType>({
    id,
    inputs,
    setInputs,
    outputKeyOrders,
    onOutputKeyOrdersChange: setOutputKeyOrders,
  })


  // single run
  const {
    isShowSingleRun,
    hideSingleRun,
    getInputVars,
    runningStatus,
    handleRun,
    handleStop,
    runInputData,
    setRunInputData,
    runResult,
  } = useOneStepRun<MetaOperatorNodeType>({
    id,
    data: inputs,
    defaultRunInputData: {},
  })

  const inputVarValues = (() => {
    const vars: Record<string, any> = {}
    Object.keys(runInputData)
      .forEach((key) => {
        vars[key] = runInputData[key]
      })
    return vars
  })()

  const setInputVarValues = useCallback((newPayload: Record<string, any>) => {
    setRunInputData(newPayload)
  }, [setRunInputData])

  return {
    readOnly,
    isDataReady,
    inputs,
    outputKeyOrders,
    handleVarsChange,
    handleRemoveVariable,
    handleAddOutputVariable,
    handleVarListChange,
    handleAddVariable,
    filterVar,
    handleMetaClassTypeChange,
    handleMethodChange,
    handleIdentifierChange,
    setTimeout,
    // single run
    isShowSingleRun,
    hideSingleRun,
    runningStatus,
    handleRun,
    handleStop,
    inputVarValues,
    setInputVarValues,
    runResult,
  }
}

export default useConfig
